package com.qdlc.p2p.biz.processor.task.collection;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.processor.event.TppDispatchValueEvent;
import com.qdlc.p2p.biz.processor.task.AbstractTaskProcessor;
import com.qdlc.p2p.biz.service.TppInvestService;
import com.qdlc.p2p.biz.task.impl.MailUtil;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.Summary;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.core.queue.ValueEvent;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.dal.model.TppModel;

/**
 * 调度任务代收
 *
 * @author ygw
 */
@Service
public class TppDispatchTaskProcessor extends AbstractTaskProcessor {
	
	private Logger logger = Logger.getLogger(TppDispatchTaskProcessor.class);

    @Override
    public boolean supports(ValueEvent event) {
        return event instanceof TppDispatchValueEvent;
    }

    @Override
    public void process0(ValueEvent event) throws TaskProcessorException {
    	TppDispatchValueEvent tppDispatchValueEvent = (TppDispatchValueEvent) event;

    	// 延时5分钟处理，防止金额未到账
		try {
            Thread.currentThread().sleep(5*60*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
		
		TppInvestService tppInvestService = (TppInvestService) BeanUtil.getBean("tppInvestService");
		String result = "success";
		try {
			TppModel tppModel = tppDispatchValueEvent.getTppModel();
			List<TppModel> taskList = new ArrayList<TppModel>();
			logger.info("自动调度处理当前ID:" + tppModel.getId());
			tppModel.setSummary(Summary.getSummaryNameByType(tppModel.getServiceType())+"(补单)");
			taskList.add(tppModel);
			tppInvestService.tppDispatchTask(taskList);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			if (e instanceof BusinessException) {// 业务异常，保存业务处理信息
				result = e.getMessage();
			} else {
				result = "系统异常，业务处理失败";
			}
			MailUtil.sendMail("自动调度任务业务队列异常",e);
		}
		if (tppDispatchValueEvent.getResultFlag() != null) {// 在需要保存系统处理信息的地方直接保存进来
			Global.TASK_RESULT_MAP.put(tppDispatchValueEvent.getResultFlag(), result);
		}
    }
}